<template>
    <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="baseInfo" tab="基本信息">
            <a-form
                ref="userRef"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                :model="userInfo"
            >
                <a-row :gutter="24" style="margin-left: 0px;margin-right: 0px;">
                    <a-col :span="12">
                        <a-form-item  label="用户名称" name="name" 
                        :rules="[{ required: true, message: '请输入用户名称!' }]">
                            <a-input v-model:value="userInfo.name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="登录帐号" name="userAccount" 
                        :rules="[{ required: true, message: '请输入登录帐号!' }]">
                            <a-input v-model:value="userInfo.userAccount"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="工号/编号" name="userNo">
                            <a-input v-model:value="userInfo.userNo"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="主部门" name="directLeader">
                            <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                                <a-space>
                                    <div style="overflow: auto;" class="tagboxs">
                                        <a-tag closable @close="handleClose()" v-for="tag in deptTags" :key="tag">
                                            {{ tag.NAME }}
                                        </a-tag>
                                    </div>
                                </a-space>
                                <n-button style="margin-left: auto;" size="small" secondary type="info" @click="openMainDeptModal">
                                    <template #icon>
                                        <n-icon><svg-icon name="touxiang" size="18" /></n-icon>
                                    </template>请选择
                                </n-button>
                            </div>
                        <a-input v-model:value="userInfo.orgId" hidden></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="性别" name="userSex">
                            <a-radio-group v-model:value="userInfo.userSex">
                                <a-radio :value=1>男</a-radio>
                                <a-radio :value=0>女</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="直属领导" name="directLeader">
                            <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                                <a-space>
                                    <div style="overflow: auto;" class="tagboxs">
                                        <a-tag closable @close="handleClose()" v-for="tag in leaderTags" :key="tag">
                                            {{ tag.NAME }}
                                        </a-tag>
                                    </div>
                                </a-space>
                                <n-button style="margin-left: auto;" size="small" secondary type="info" @click="openModal">
                                    <template #icon>
                                        <n-icon><svg-icon name="touxiang" size="18" /></n-icon>
                                    </template>请选择
                                </n-button>
                            </div>
                        <a-input v-model:value="userInfo.directLeader" hidden></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="职务" name="userStaff">
                            <a-input v-model:value="userInfo.userStaff"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="职级" name="staffLevel">
                            <a-input v-model:value="userInfo.staffLevel"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="联系电话" name="phoneNumber">
                            <a-input v-model:value="userInfo.phoneNumber"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="邮寄地址" name="postAddress">
                            <a-input v-model:value="userInfo.postAddress"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="双因子验证" name="doubleValidation">
                            <a-input v-model:value="userInfo.doubleValidation"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="关联帐号" name="relatedAccount">
                            <a-input v-model:value="userInfo.relatedAccount"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="关键字" name="keyWords">
                            <a-input v-model:value="userInfo.keyWords"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="是否启用" name="IS_ENABLED">
                            <a-radio-group v-model:value="userInfo.IS_ENABLED">
                                <a-radio :value=0>不启用</a-radio>
                                <a-radio :value=1>启用</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item  label="是否与业务相关" name="IS_BUSINESS">
                            <a-radio-group v-model:value="userInfo.IS_BUSINESS">
                                <a-radio :value=0>否</a-radio>
                                <a-radio :value=1>是</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12" >
                        <a-form-item  label="排序号" name="personSort">
                            <a-input-number v-model:value="userInfo.personSort"></a-input-number>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" >
                        <a-form-item  :label-col="{ span: 3 }"
                        :wrapper-col="{ span: 21 }"  label="备注" name="remark">
                            <a-textarea v-model:value="userInfo.remark"></a-textarea>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" >
                        <a-form-item  :label-col="{ span: 3 }"
                        :wrapper-col="{ span: 21 }"  label="人员图片" name="picture">
                        <a-upload
                            v-model:file-list="fileList"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :action="api.uploadfiles"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                        >
                        <img v-if="userInfo.picture" :src="userInfo.picture" alt="avatar" />
                         <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">上传图片</div>
                        </div>
                        </a-upload>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-tab-pane>
        <a-tab-pane v-if="userInfo.userId!==''&&userInfo.userId!==undefined" key="depts" tab="所属部门">
            <a-button type="primary" @click="openDeptModal"> 新增 </a-button>
            <DeptTable :dataSource="userDepts" :columns="deptColumns" >
            </DeptTable>
        </a-tab-pane>
        <a-tab-pane v-if="userInfo.userId!==''&&userInfo.userId!==undefined" key="posts" tab="所属岗位">
            <a-form
                ref="userRef"
                :label-col="{ span: 2 }"
                :wrapper-col="{ span: 22 }"
                :model="userInfo"
            >
            <!-- <a-form-item  label="主岗位" name="mainPost">
                <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                    <a-space>
                        <div style="overflow: auto;" class="tagboxs">
                            <a-tag closable @close="handleClose()" v-for="tag in mainPostTags" :key="tag">
                                {{ tag.NAME }}
                            </a-tag>
                        </div>
                    </a-space>
                    <n-button style="margin-left: auto;" size="small" secondary type="info" @click="openMainStationModal">
                        <template #icon>
                            <n-icon><svg-icon name="touxiang" size="18" /></n-icon>
                                </template>请选择
                            </n-button>
                        </div>
                    <a-input v-model:value="userInfo.mainPost" hidden></a-input>
                </a-form-item> -->
            </a-form>
            <a-button type="primary" @click="openStationModal"> 新增 </a-button>
            <StationTable :dataSource="userStations" :columns="postsColumns" >
            </StationTable>
        </a-tab-pane>
    </a-tabs>
            
</template>
<script lang="tsx" setup>
    import { reactive, h,ref,unref, defineComponent } from 'vue';
    import { message, type FormInstance } from 'ant-design-vue';
    import { useModal } from '@/hooks/useModal/useModal';
    import type { LoadDataParams } from '@/components/core/dynamic-table';
    import { blankData } from './formSchemas';
    import userSingle from '@/components/system/orgUserSingle/userSingle.vue';
    import stationModel from '@/components/system/orgStationModel/index.vue';
    import deptModel from '@/components/system/orgDeptModel/index.vue';
    import { useTable } from '@/components/core/dynamic-table';
    import { positionListByUser } from '@/api/organization/station/station';
    import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
    import { PlusOutlined, LoadingOutlined, ConsoleSqlOutlined } from '@ant-design/icons-vue';
    import { getDeptListByUser } from '@/api/organization/depts/depts';
    import api from '@/core/permission/modules/form/index';

    defineComponent({
        userSingle,
        stationModel,
        deptModel
    })
    interface UserItem{
      defaultData?:any;
    };
    const props = withDefaults(defineProps<UserItem>(),{
        defaultData:{
            userInfo:{...blankData},
        }
    });
    const userInfo = reactive(props.defaultData.userInfo);
    const [ModalRender, modalRef] = useModal();
    //人员所属部门
    const userDepts=ref([]);
    //人员所属岗位
    const userStations=ref([]);
    //人员拥有的公共岗
    const userPubPosts=ref([]);

    //人员头像
    const fileList = ref([]);
    const loading = ref<boolean>(false);
    //主部门
    const deptTags=ref<any>([]);
    //直属领导tags
    const leaderTags=ref<any>([]);
    //主岗位tags
    const mainPostTags=ref<any>([]);
    const userSingleRef = ref<FormInstance>();
    //主岗位ref
    const mainPostRef = ref<FormInstance>();
    //主部门ref
    const deptSingleRef = ref<FormInstance>();
    //辅助岗位ref
    const postRef = ref<FormInstance>();
    const userRef=ref<FormInstance>();
    const activeKey=ref("baseInfo");

    const loadTagData=async()=>{
        const res=await getDeptListByUser({userId:userInfo.userId});
        if(res.code=="200"){
            
            userDepts.value=res.rows;
        }
        console.log(userDepts.value,"userDepts.value")
        const data = await positionListByUser({
            userId: userInfo.userId.length ? userInfo.userId : '',
        });
        if(data.error=="200"){
            userStations.value=data.result;
        }
        console.log(userInfo,"userinfo11111")
        if(userInfo.directLeader!==''&&userInfo.directLeader!==''&&userInfo.directLeader!=undefined){
            const tag={
                NO:userInfo.directLeader,
                NAME:userInfo.leaderName,
                ORG_TYPE:'user'
            }
            leaderTags.value.push(tag);
        }
        if(userInfo.orgId!==''&&userInfo.orgId!==''&&userInfo.orgId!=undefined){
            const tag={
                NO:userInfo.orgId,
                NAME:userInfo.deptName,
                ORG_TYPE:'user'
            }
            deptTags.value.push(tag);
        }
        /**
         * 显示主岗位信息
         */
         if(userInfo.mainPost.length>0){
            const mainPostInfo={
                NAME: userInfo.mainPostName,
                NO: userInfo.mainPost,
                ORG_TYPE: 'station'
            };
            mainPostTags.value.push(mainPostInfo);
        }
    };
    loadTagData();
    const editDrawerBindValue = reactive({
        defaultSelectData: [],
        depts:[],
        runType:'',
        modelType:'',
    });
    const openMainDeptModal = async()=>{
        editDrawerBindValue.modelType="single";
        ModalRender.show({
        title: '选择主部门',
        width: '70%',
        // 是否显示右上角确定取消
        defaultExtra: true,
        destroyOnClose: true,
        content: () => {
            return <deptModel  ref={deptSingleRef} defaultData={unref(editDrawerBindValue)}></deptModel>;
        },
        // 确定方法执行
        onOk: async (values) => {
            const res = await deptSingleRef.value?.handleSubmit();
            if (!res) return;
            deptTags.value=res;
            userInfo.orgId=res[0].NO;
            const index = userDepts.value.filter(option => option.code ===res[0].NO);
            if(index.length<=0){
                const dept= {
                    id:res[0].NO,
                    name:res[0].NAME,
                    ORG_TYPE:'dept'
                };
                userDepts.value.push(dept) 
            }
        },
        });
    };
    const openModal = async()=>{
        ModalRender.show({
        title: '选择直属领导',
        width: '70%',
        // 是否显示右上角确定取消
        defaultExtra: true,
        destroyOnClose: true,
        content: () => {
            return <userSingle  ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
        },
        // 确定方法执行
        onOk: async (values) => {
            const res = await userSingleRef.value?.handleSubmit();
            if (!res) return;
            leaderTags.value.push(res);
            userInfo.directLeader=res.NO;
        },
        });
    };
    //设置部门
    const openDeptModal = async()=>{
        editDrawerBindValue.modelType="more";
        editDrawerBindValue.defaultSelectData=[];
        if(userDepts.value.length>0){
            const deptInfo=userDepts.value.map((item)=>{
                return {
                    code:item.code,
                    name:item.name,
                    ORG_TYPE:'dept'
                }; 
            })
            editDrawerBindValue.defaultSelectData.push(deptInfo);
        }
        ModalRender.show({
            title: '选择部门',
            width: '70%',
            // 是否显示右上角确定取消
            defaultExtra: true,
            destroyOnClose: true,
            content: () => {
                return <deptModel  ref={mainPostRef} defaultData={unref(editDrawerBindValue)}></deptModel>;
            },
            // 确定方法执行
            onOk: async () => {
                const res = await mainPostRef.value?.handleSubmit();
                if (!res) return;
                res.map((item)=>{
                    const index = userDepts.value.filter(option => option.code ===item.code);
                    if(index.length<=0){
                        const dept= {
                            id:item.code,
                            name:item.name,
                            ORG_TYPE:'dept'
                        };
                        userDepts.value.push(dept) 
                    }
                })
            },
        });
    };
    //设置主岗位
    const openMainStationModal = async()=>{
        editDrawerBindValue.modelType="single";
        editDrawerBindValue.defaultSelectData=[];
        if(userInfo.mainPost!=""&&userInfo.mainPost!=undefined){
            const mainPostInfo={
                NAME: '',
                NO: userInfo.mainPost,
                ORG_TYPE: 'station'
            };
            editDrawerBindValue.defaultSelectData.push(mainPostInfo);
        }
        ModalRender.show({
            title: '选择主岗位',
            width: '70%',
            // 是否显示右上角确定取消
            defaultExtra: true,
            destroyOnClose: true,
            content: () => {
                return <stationModel  ref={mainPostRef} defaultData={unref(editDrawerBindValue)}></stationModel>;
            },
            // 确定方法执行
            onOk: async () => {
                const res = await mainPostRef.value?.handleSubmit();
                if (!res) return;
                mainPostTags.value=res;
                userInfo.mainPost=res[0].NO;
            },
        });
    };
    //设置辅助岗位
    const openStationModal = async()=>{
        console.log(userDepts.value,"00000000000000")
        editDrawerBindValue.modelType="more";
        editDrawerBindValue.depts=userDepts.value;
        editDrawerBindValue.defaultSelectData=[];
        if(userStations.value.length>0){
            const postInfo=userStations.value.map((item)=>{
                return {
                    id:item.code,
                    name:item.name,
                    ORG_TYPE:'station'
                }; 
            })
                editDrawerBindValue.defaultSelectData.push(postInfo);
        }
        ModalRender.show({
            title: '选择辅岗位',
            width: '70%',
            // 是否显示右上角确定取消
            defaultExtra: true,
            destroyOnClose: true,
            content: () => {
                return <stationModel  ref={postRef} defaultData={unref(editDrawerBindValue)}></stationModel>;
            },
            // 确定方法执行
            onOk: async () => {
                const res = await postRef.value?.handleSubmit();
                if (!res) return;
                res.map((item)=>{
                    const index = userStations.value.filter(option => option.code ===item.NO);
                    if(index.length<=0){
                        const station= {
                            code:item.NO,
                            name:item.NAME,
                            ORG_TYPE:'station'
                        };
                        userStations.value.push(station) 
                    }
                })
            },
        });
    };
    const handleChange = (info: UploadChangeParam) => {
        console.log(info,"uploadinfo111111111111111")
        if (info.file.status === 'uploading') {
            loading.value = true;
            return;
        }
        if (info.file.status === 'done') {
            if(info.file.response.error=="200"){
                userInfo.picture=info.file.response.result.filePath;
            }
            else{
                loading.value = false;
                message.error("上传失败");
            }
            
        }
        if (info.file.status === 'error') {
            loading.value = false;
            message.error("上传失败");
        }
    };
    const beforeUpload = (file: UploadProps['fileList'][number]) => {
        return new Promise<boolean | File>((resolve) => {
            const img = new Image();
            img.src = URL.createObjectURL(file);
            img.onload = () => {
                URL.revokeObjectURL(img.src); 
                if (img.width > 70 || img.height > 70) {
                    message.error("图片尺寸不得大于70x70");
                    resolve(false);
                    return;
                }
                else{
                    resolve(true);
                    return;
                }
            }
        });
        
        
    };
    function getBase64(img: Blob, callback: (base64Url: string) => void) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    }
    const [DeptTable] = useTable({
        size: 'small',
        rowKey: 'id',
        bordered: true,
        showIndex: true,
        search: false,
        showToolBar: false,
    });
    const deptColumns = [
        {
            title: '部门名称',
            dataIndex: 'name',
            align: 'center',
        },
        {
            title: '部门ID',
            dataIndex: 'id',
            align: 'center',
        }
    ];
    const [StationTable] = useTable({
        size: 'small',
        rowKey: 'id',
        bordered: true,
        showIndex: true,
        search: false,
        showToolBar: false,
    });
    const postsColumns = [
        {
            title: '岗位名称',
            dataIndex: 'name',
            align: 'center',
        },
        {
            title: '岗位编码',
            dataIndex: 'code',
            align: 'center',
        }
    ];
    const handleClose=()=>{
        leaderTags.value=[];
        userInfo.leader="";
    }
    const onSubMit = () => {
        userInfo.depts=userDepts.value;
        userInfo.posts=userStations.value;
        console.log(userInfo,"99999999999999999999999999999999")
        return [userInfo,userRef];
    };

    defineExpose({
        handleSubmit: onSubMit,
    });
</script>